// 引入数据管理工具
const db = require('../../utils/db.js');

Page({
  data: {
    userInfo: {
      avatarUrl: '/images/avatar1.png',
      nickName: '用户名',
      signature: '这个人很懒，什么都没有留下'
    },
    stats: {
      confessions: 0,
      likes: 0,
      comments: 0
    },
    menuList: [
      {
        id: 1,
        icon: '/images/my-posts.png',
        title: '我的表白',
        url: '/pages/my-confessions/my-confessions'
      },
      {
        id: 2,
        icon: '/images/my-likes.png',
        title: '我的点赞',
        url: '/pages/my-likes/my-likes'
      },
      {
        id: 3,
        icon: '/images/settings.png',
        title: '设置',
        url: '/pages/settings/settings'
      },
      {
        id: 4,
        icon: '/images/agreement.png',
        title: '用户协议',
        url: '/pages/agreement/agreement'
      },
      {
        id: 5,
        icon: '/images/privacy.png',
        title: '隐私政策',
        url: '/pages/privacy/privacy'
      },
      {
        id: 6,
        icon: '/images/about.png',
        title: '关于我们',
        url: '/pages/about/about'
      }
    ]
  },

  onLoad() {
    // 获取用户信息
    this.getUserInfo();
    // 获取用户统计数据
    this.getUserStats();
  },

  // 获取用户信息
  getUserInfo() {
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: {
          avatarUrl: app.globalData.userInfo.avatarUrl,
          nickName: app.globalData.userInfo.nickName,
          signature: this.data.userInfo.signature
        }
      });
    } else {
      // 如果没有用户信息，尝试从本地存储获取
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.setData({
          userInfo: userInfo
        });
      }
    }
  },

  // 获取用户统计数据
  async getUserStats() {
    try {
      // 这里应该从数据库获取真实的统计数据
      // 暂时使用模拟数据
      this.setData({
        stats: {
          confessions: 5,
          likes: 128,
          comments: 26
        }
      });
    } catch (error) {
      console.error('获取用户统计数据失败:', error);
    }
  },

  // 跳转到菜单页面
  goToPage(e) {
    const url = e.currentTarget.dataset.url;
    wx.navigateTo({
      url: url
    });
  },

  // 编辑个人资料
  editProfile() {
    wx.navigateTo({
      url: '/pages/edit-profile/edit-profile'
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 清除用户信息
          wx.removeStorageSync('userInfo');
          
          // 重置全局用户信息
          const app = getApp();
          app.globalData.userInfo = null;
          
          wx.showToast({
            title: '已退出登录',
            icon: 'success'
          });
          
          // 跳转到首页
          setTimeout(() => {
            wx.switchTab({
              url: '/pages/index/index'
            });
          }, 1500);
        }
      }
    });
  }
})